# -*- coding:utf-8 -*-
import os
import requests
import hashlib
import time
import datetime
import copy
import logging
import random
from urllib.parse import urlencode

import smtplib
from email.mime.text import MIMEText


logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)

# API_URL
LIKIE_URL = "http://c.tieba.baidu.com/c/f/forum/like"
TBS_URL = "http://tieba.baidu.com/dc/common/tbs"
SIGN_URL = "http://c.tieba.baidu.com/c/c/forum/sign"
PUBLISH_URL = 'https://tieba.baidu.com/f/commit/thread/add'

ENV = os.environ

HEADERS = {
    'Host': 'tieba.baidu.com',
    'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.71 Safari/537.36',
}
SIGN_DATA = {
    '_client_type': '2',
    '_client_version': '9.7.8.0',
    '_phone_imei': '000000000000000',
    "net_type": "1",
}

# VARIABLE NAME
COOKIE = "Cookie"
BDUSS = "BDUSS"
EQUAL = r'='
EMPTY_STR = r''
TBS = 'tbs'
PAGE_NO = 'page_no'
ONE = '1'
TIMESTAMP = "timestamp"
DATA = 'data'
FID = 'fid'
SIGN_KEY = 'tiebaclient!!!'
UTF8 = "utf-8"
SIGN = "sign"
KW = "kw"

class tieba:
    def __init__(self, bduss):
        self.bduss = bduss
        self.tbs = self.get_tbs(bduss)
        self.pub_freq = (30*60, 60*60) # 30-60分钟
        # self.pub_freq = (1, 6) # 30-60分钟
        self.last_time = None
        self.verify = False
        self.verify = True
        self.proxies = None
        #self.proxies = {'https': 'http://127.0.0.1:8888'}

    def get_tbs(self, bduss):
        logger.info("获取tbs开始")
        headers = copy.copy(HEADERS)
        headers.update({COOKIE: EMPTY_STR.join([BDUSS, EQUAL, bduss])})
        try:
            tbs = requests.get(url=TBS_URL, headers=headers, timeout=5).json()[TBS]
        except Exception as e:
            logger.error("获取tbs出错" + e)
            logger.info("重新获取tbs开始")
            tbs = requests.get(url=TBS_URL, headers=headers, timeout=5).json()[TBS]
        logger.info("获取tbs结束")
        return tbs


    def get_favorite(self):
        logger.info("获取关注的贴吧开始")
        # 客户端关注的贴吧
        returnData = {}
        i = 1
        data = {
            'BDUSS': self.bduss,
            '_client_type': '2',
            '_client_id': 'wappc_1534235498291_488',
            '_client_version': '9.7.8.0',
            '_phone_imei': '000000000000000',
            'from': '1008621y',
            'page_no': '1',
            'page_size': '200',
            'model': 'MI+5',
            'net_type': '1',
            'timestamp': str(int(time.time())),
            'vcode_tag': '11',
        }
        data = self.encodeData(data)
        try:
            res = requests.post(url=LIKIE_URL, data=data, timeout=5, proxies=self.proxies, verify=self.verify).json()
        except Exception as e:
            logger.error("获取关注的贴吧出错" + e)
            return []
        returnData = res
        if 'forum_list' not in returnData:
            returnData['forum_list'] = []
        if res['forum_list'] == []:
            return {'gconforum': [], 'non-gconforum': []}
        if 'non-gconforum' not in returnData['forum_list']:
            returnData['forum_list']['non-gconforum'] = []
        if 'gconforum' not in returnData['forum_list']:
            returnData['forum_list']['gconforum'] = []
        while 'has_more' in res and res['has_more'] == '1':
            i = i + 1
            data = {
                'BDUSS': bduss,
                '_client_type': '2',
                '_client_id': 'wappc_1534235498291_488',
                '_client_version': '9.7.8.0',
                '_phone_imei': '000000000000000',
                'from': '1008621y',
                'page_no': str(i),
                'page_size': '200',
                'model': 'MI+5',
                'net_type': '1',
                'timestamp': str(int(time.time())),
                'vcode_tag': '11',
            }
            data = self.encodeData(data)
            try:
                res = requests.post(url=LIKIE_URL, data=data, timeout=5, proxies=self.proxies, verify=self.verify).json()
            except Exception as e:
                logger.error("获取关注的贴吧出错" + e)
                continue
            if 'forum_list' not in res:
                continue
            if 'non-gconforum' in res['forum_list']:
                returnData['forum_list']['non-gconforum'].append(res['forum_list']['non-gconforum'])
            if 'gconforum' in res['forum_list']:
                returnData['forum_list']['gconforum'].append(res['forum_list']['gconforum'])

        self.favorites = {}
        for i in returnData['forum_list']['non-gconforum']:
            if isinstance(i, list):
                for j in i:
                    if isinstance(j, list):
                        for k in j:
                            # t.append(k)
                            self.favorites[k['name']] = k['id']
                    else:
                        # t.append(j)
                        self.favorites[j['name']] = j['id']
            else:
                # t.append(i)
                self.favorites[i['name']] = i['id']
        for i in returnData['forum_list']['gconforum']:
            if isinstance(i, list):
                for j in i:
                    if isinstance(j, list):
                        for k in j:
                            # t.append(k)
                            self.favorites[k['name']] = k['id']
                    else:
                        # t.append(j)
                        self.favorites[j['name']] = j['id']
            else:
                # t.append(i)
                self.favorites[i['name']] = i['id']
        logger.info("获取关注的贴吧结束")
        return self.favorites


    def encodeData(self, data):
        s = EMPTY_STR
        keys = data.keys()
        for i in sorted(keys):
            s += i + EQUAL + str(data[i])
        sign = hashlib.md5((s + SIGN_KEY).encode(UTF8)).hexdigest().upper()
        data.update({SIGN: str(sign)})
        return data


    def client_sign(self, tb_id, tb_name):
        if len(tb_id) == 0:
            tb_id = self.favorites[tb_name]
        # 客户端签到
        logger.info("开始签到贴吧：" + tb_name)
        data = copy.copy(SIGN_DATA)
        data.update({BDUSS: self.bduss, FID: tb_id, KW: tb_name, TBS: self.tbs, TIMESTAMP: str(int(time.time()))})
        data = self.encodeData(data)
        res = requests.post(url=SIGN_URL, data=data, timeout=5, proxies=self.proxies, verify=self.verify).json()
        return res

    # 列表
    def list(self,  tb_name):
        logger.info("开始发贴：" + tb_name)
        headers = copy.copy(HEADERS)
        print(self.bduss)
        #headers.update({COOKIE: EMPTY_STR.join([BDUSS, EQUAL, self.bduss]),
        headers.update({COOKIE: 'BDUSS=nZvTmhmVDQtfnBDRjRWdTFWTFRPeW53NnFPUmwyYjJxT2lxUzF4MHdrZWdHdzFrSVFBQUFBJCQAAAAAAQAAAAEAAAA3h818eHlsb25nenp6enoAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAKCO5WOgjuVjN; BDUSS_BFESS=nZvTmhmVDQtfnBDRjRWdTFWTFRPeW53NnFPUmwyYjJxT2lxUzF4MHdrZWdHdzFrSVFBQUFBJCQAAAAAAQAAAAEAAAA3h818eHlsb25nenp6enoAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAKCO5WOgjuVjN; STOKEN=437ba476e153bb8fce4d0289df32ff3252ae3cd33740125698fff6ab0c869ba4',
                    'Referer':'https://tieba.baidu.com/f?kw=%s&fr=index' % quote(tb_name)})
        url = 'https://tieba.baidu.com/f?kw=%s&ie=utf-8&tab=main'% quote(tb_name)
        res = requests.get(url=url, headers=headers, timeout=5, proxies=self.proxies,verify=self.verify)
        print(res.text)
        return res

    # 回复
    def answer(self, tb_id, tb_name, title, content):
        # 客户端签到
        logger.info("开始回复：" + tb_name)
        headers = copy.copy(HEADERS)
        # headers.update({COOKIE: EMPTY_STR.join([BDUSS, EQUAL, self.bduss]),
        headers.update({COOKIE: 'BDUSS=nZvTmhmVDQtfnBDRjRWdTFWTFRPeW53NnFPUmwyYjJxT2lxUzF4MHdrZWdHdzFrSVFBQUFBJCQAAAAAAQAAAAEAAAA3h818eHlsb25nenp6enoAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAKCO5WOgjuVjN',
                        'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
                        'Referer':'https://tieba.baidu.com/p/8253860302?pid=146812181378&cid=0'})

        data = {
            'tbs': self.tbs,
            'fid': tb_id,
            'kw': tb_name.encode('utf-8'),
            'content': content,
            'title': title,
            'rich_text': '1',
            'geetest_success': '0'
        }
        data1= 'ie=utf-8&kw=%E9%98%BF%E9%87%8C%E4%BA%91%E7%9B%98&fid=27417212&tid=8253860302&vcode_md5=&floor_num=1&rich_text=1&tbs=099671ba69af157f1675996030&content=456&basilisk=1&files=%5B%5D&mouse_pwd=46%2C44%2C41%2C55%2C42%2C35%2C41%2C47%2C18%2C42%2C55%2C43%2C55%2C42%2C55%2C43%2C55%2C42%2C55%2C43%2C55%2C42%2C55%2C43%2C55%2C42%2C55%2C43%2C18%2C40%2C35%2C42%2C47%2C45%2C18%2C42%2C34%2C41%2C43%2C55%2C42%2C43%2C35%2C43%2C16759960316271&mouse_pwd_t=1675996031627&mouse_pwd_isclick=1&nick_name=&ua=Mozilla%2F5.0+(Windows+NT+10.0%3B+Win64%3B+x64)+AppleWebKit%2F537.36+(KHTML%2C+like+Gecko)+Chrome%2F109.0.0.0+Safari%2F537.36+Edg%2F109.0.1518.78&ev=comment&biz%5Bpo%5D=tb.1.e2032f36.VU9bIBKKrm9gGV6g1NbzSw&jt=&__type__=reply&geetest_success=0&_BSK=SxtXBxULQlMGCFZWBAQGShNVBhcDGUJCRlUcG04HFQtAL2N1LUQdF1tUEwwXQUtMUxwRUQIbAxYGAVZRGhsSVBMPF1cIBAcZG04EEgkSfmx1ehUdQAwEG1tEGQMDXh0HDgEMEBoYAgACABUDBARLTR4IUVIDGQJSAB8bHQoJDxwKBAgQFR4DCVZNAQFYTx0dBlcDBBsNCAofHBsBAQ8AGgEDVkgaEVBXBw0bVwcABxwVEQ8ABBwBDw8GHhNOQ1sKQ1wRQUUTVBoVWAgbDBJRUUNQVV9EWj0Aek9RDFYXG0RFBxUPG19DXlBEWVZXFkNeMRVEUA8BGRwXHRFtWVRNUEBVE1NfXVxrF0xATRROVUQLFwdKRl9ZUVZOGkNWXFYVXVlURA8EWE1NCFBYUkpdWVRUTVBZXh9TRUpNWVp0DgRbXA8SQhlfD0JCWEdAFVpfUFFEUFZYVVAQTVtcDxNTVEVKQVNFRlZXV1xRUUIVSlVFXg4NVFgTFR1GQwdFQ0RXWEsaRFxfXFtYRBtCFgBCTBJKUllYFVRSG1NLWFtVQBxcXFdRQ1lOFVlJTQlBUFkDQxpHVEtcWEQRHBJJCxQNEzUIWApTRB0XVlUTDBdTWFVFVR8SQggbDBVXFw9VTQgJXxVFB19SWFgREBZLE2teWE1fQVRCAlldBDsRSBVKE0UEFwMZQkJGVRwbWAIVC0IHV1USAx0XR1cTDBUQDnsTAgFEUkocBAUUUSATC1NWCAwBUQBUVgMAWFABBgdWCA8BAghbVwYKUUMDBxJRdRQbF1cLFAoTREJMXBoVXFdDDBkVFERQG0RaBBUPGw0PHAYAHAwIFBsTD1UUA0NWHQQHVQgUGxdXChQKEwIACA4GAgBTTRRNU0QLFQZQBgMODA8IBQAfEkAKGwwXVwMNRVxNREQEFVwTe1hPUFVaURwFHgkZHmBYDAVZThJGf2EXVwEYBw4Zbl9eBQQLGUEAAxhCIEZJDQNmUFUtWEIYAAoOGAMFEBhycWJ6fU5BWlAKAxFyUgVaWR4VelFEX15VHwgJDxkBTFEYCUE1UFNWFFgZAgYOFwUGE3VUXhYHBwhMURgIVFcJGwBeExoVXAgbDBBHQkVcFRRcAEBbFl8ACkJQG0RQBxUPGQgPAgMcEkoIFA0RU1EOCU1EXQQVXBNMXxh6dxQcEVQBGwMUeWQuLRQVQxECFw1GV1dbRlwVFFUCEgoZCwYGBlJUBwgc'
        data1= 'ie=utf-8&kw=%E9%98%BF%E9%87%8C%E4%BA%91%E7%9B%98&fid=27417212&tid=8253860302&vcode_md5=&floor_num=1&rich_text=1&tbs=099671ba69af157f1675996030&content=123&basilisk=1'
        url = 'https://tieba.baidu.com/f/commit/post/add'
        res = requests.post(url=url, headers=headers, data=data1, timeout=5, proxies=self.proxies, verify=self.verify)
        print(res.status_code,res.text)
        return res

    # 发帖
    def publish(self, tb_id, tb_name, title, content):
        while True:
            now = datetime.datetime.now()
            pub_freq_second = random.randint(self.pub_freq[0], self.pub_freq[1])
            if not self.last_time is None and (now-self.last_time).seconds < pub_freq_second:
                time.sleep(10)
            else:
                self.last_time = now
                break

        if len(tb_id) == 0:
            tb_id = self.favorites[tb_name]
        # 客户端签到
        logger.info("开始发贴：" + tb_name)
        headers = copy.copy(HEADERS)
        headers.update({COOKIE: EMPTY_STR.join([BDUSS, EQUAL, self.bduss]),
                        'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
                        'Referer':'https://tieba.baidu.com/f?kw=%s' % tb_name.encode('utf-8')})

        timestamp = str(int(time.time()*1000))
        mouse_crack= '55,61,61,41,49,48,52,53,12,52,41,53,41,52,41,53,41,52,41,53,12,49,55,53,49,60,61,51,12,52,55,61,53,41,61,53,53,'
        data = {
            "ie": "utf-8",
            "tid": 0,
            "floor_num": 0,
             "basilisk": 1,
             "mouse_pwd_isclick":0,
             "__type__": "thread",
             "mouse_pwd_t": timestamp,
             'mouse_pwd' :  mouse_crack[random.randint(0, len(mouse_crack)) - 1] + timestamp,
             "vcode_md5": '',   #change
            'tbs': self.tbs,
            'fid': tb_id,
            'kw': tb_name.encode('utf-8'),
            'content': content,
            'title': title,
            'rich_text': '1',
            'geetest_success': '0'
        }

        res = requests.post(url=PUBLISH_URL, headers=headers, data=data, timeout=5, proxies=self.proxies, verify=self.verify).json()
        return res

    # 发帖到所有贴吧
    def publish_all(self, title, content):
        for tb_name, tb_id in self.favorites.items():
            self.publish(tb_id, tb_name, title, content)

def send_email(sign_list):
    if ('HOST' not in ENV or 'FROM' not in ENV or 'TO' not in ENV or 'AUTH' not in ENV):
        logger.error("未配置邮箱")
        return
    HOST = ENV['HOST']
    FROM = ENV['FROM']
    TO = ENV['TO'].split('#')
    AUTH = ENV['AUTH']
    length = len(sign_list)
    subject = f"{time.strftime('%Y-%m-%d', time.localtime())} 签到{length}个贴吧"
    body = """
    <style>
    .child {
    background-color: rgba(173, 216, 230, 0.19);
    padding: 10px;
    }

    .child * {
    margin: 5px;
    }
    </style>
    """
    for i in sign_list:
        body += f"""
        <div class="child">
            <div class="name"> 贴吧名称: { i['name'] }</div>
            <div class="slogan"> 贴吧简介: { i['slogan'] }</div>
        </div>
        <hr>
        """
    msg = MIMEText(body, 'html', 'utf-8')
    msg['subject'] = subject
    smtp = smtplib.SMTP()
    smtp.connect(HOST)
    smtp.login(FROM, AUTH)
    smtp.sendmail(FROM, TO, msg.as_string())
    smtp.quit()


if __name__ == '__main__':
    bduss_list = ['Z1TzdTR1MyNUdRZG85eW5WdGdqcHZHeTB2QWtLenNyaFJTcUZvTm4yeGNOZlJqSVFBQUFBJCQAAAAAAAAAAAEAAAC698GkWFlMb25nenpaAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAFyozGNcqMxjRW']
    bduss_list = ['luNUlsWHY2WGxmWEQ2S1Rqa3YzcmN-N3lRQVY4VlFvR0Jhfkg3a09Vd1VmQXBrSUFBQUFBJCQAAAAAAQAAAAEAAAA3h818eHlsb25nenp6enoAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABTv4mMU7-Jjel', 'Z1TzdTR1MyNUdRZG85eW5WdGdqcHZHeTB2QWtLenNyaFJTcUZvTm4yeGNOZlJqSVFBQUFBJCQAAAAAAAAAAAEAAAC698GkWFlMb25nenpaAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAFyozGNcqMxjRW']
    bduss_list = ['jQ4VFNnSTR-VERyWHBiZE5mclhjT0lLSHhub0NZWDRsb3ZVdTF5TEVUaVJQeFJrSVFBQUFBJCQAAAAAAQAAAAEAAADB1A19bG9uZ3p6WjgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAJGy7GORsuxjM']
    for n, bduss in enumerate(bduss_list):
        tb = tieba(bduss)
        favorites = tb.get_favorite()
        print(favorites)
        logger.info("开始签到第" + str(n) + "个用户" + bduss)
        for name, id in favorites.items():
            time.sleep(random.randint(1,5))
            tb.client_sign(id, name)
        logger.info("完成第" + str(n) + "个用户签到")
        # while True:
            # print(tb.publish('', '阿里云盘', '最新最火电视剧持续更新中', ''))

        #大宋提刑官 (2005):[br][url]https://www.aliyundrive.com/s/ZKmHsXwd5Tu[/url]
        # with open('share_info.txt', 'r', encoding="utf-8") as f:
            # txt = f.read()
        # print(tb.publish('', '阿里云盘', '最新最火电视剧持续更新中', txt))
    #send_email(favorites)
    logger.info("所有用户签到结束")
